const express = require('express');
const router = express.Router();
const utils = require("../utils/index.js");
const pools = require("../utils/pools.js");
const {RANDOM} = require("mysql/lib/PoolSelector");

// 获取销售订单列表
router.post('/list', async (req, res) => {
    try {
        const { order_number, customer_name, vehicle_model, order_status, page = 1, size = 10 } = req.body;
        let sql = 'SELECT * FROM salesorder WHERE 1=1';
        const params = [];

        // 构建搜索条件
        if (order_number) {
            sql += ' AND order_number LIKE ' + '"%' + order_number + '%"';
        }
        if (customer_name) {
            sql += ' AND customer_name LIKE ' + '"%' + customer_name + '%"';
        }
        if (vehicle_model) {
            sql += ' AND vehicle_model LIKE ' + '"%' + vehicle_model + '%"';
        }
        if (order_status) {
            sql += ' AND order_status = "' + order_status + '"';
        }
        sql +=` ORDER BY id ASC`;


        // 获取总数
        const countSql = sql.replace('SELECT *', 'SELECT COUNT(*) as total');

        // 执行查询
        let {total}=await utils.getSum({sql,name:"salesorder",res,req});
        sql=utils.pageSize(sql,page,size);
        let {result}=await pools({sql,res,req});
        res.send(utils.returnData({data: result,total}));


    } catch (error) {
        console.error('获取订单列表失败:', error);
        res.json(utils.error('获取订单列表失败'));
    }
});

// 获取订单详情
router.post('/detail', async (req, res) => {
    try {
        const { id } = req.body;
        if (!id) {
            return res.json(utils.error('订单ID不能为空'));
        }

        const sql = `
            SELECT od.* 
            FROM order_detail od 
            WHERE od.order_id = ?
        `;

        await pools({
            sql,
            val: [id],
            res,
            req,
            run: false
        });
    } catch (error) {
        console.error('获取订单详情失败:', error);
        res.json(utils.error('获取订单详情失败'));
    }
});

// 更新订单状态
router.post('/updateStatus', async (req, res) => {
    try {
        const { id, order_status } = req.body;

        // 参数验证
        if (!id || !order_status) {
            return res.json(utils.error('订单ID和状态不能为空'));
        }

        const sql = 'UPDATE salesorder SET order_status = ? WHERE id = ?';

        await pools({
            sql,
            val: [order_status, id],
            res,
            req,
            run: false
        });
    } catch (error) {
        console.error('更新订单状态失败:', error);
        res.json(utils.error('更新订单状态失败'));
    }
});

function formatDate() {
    const date = new Date(); // 获取当前日期和时间
    const year = date.getFullYear(); // 获取年份
    const month = String(date.getMonth() + 1).padStart(2, '0'); // 获取月份，+1 是因为月份是从 0 开始的，padStart 用于补零
    const day = String(date.getDate()).padStart(2, '0'); // 获取日期，padStart 用于补零
    return `${year}${month}${day}` + Math.floor(1000 + Math.random() * 9000); // 拼接成 yyyyMMdd 格式
}

// 添加订单
router.post('/add', async (req, res) => {
    try {

        const {
            customer_name,
            vehicle_model,
            order_status,
            payment_status,
            // 订单详情数据
            price,
            favorable_price,
            car_detail,
        } = req.body;

        // 参数验证
        if (!customer_name || !vehicle_model) {
            return res.json(utils.error('客户姓名和车型不能为空'));
        }

        // 生成订单号 (年月日 + 6位随机数)
        const order_number = "SO" + formatDate();


            // 1. 插入主订单表
            let sql = `
                INSERT INTO salesorder 
                (order_number, customer_name, vehicle_model, order_status, payment_status, order_time) 
                VALUES (?, ?, ?, ?, ?, NOW())
            `;
      await pools({sql, val:[
                order_number,
                customer_name,
                vehicle_model,
                order_status || 'pending',
                payment_status || 'unpaid'
            ],run:true,res,req}).then(orderResult => {
          // 2. 插入订单详情表
          sql = `
                INSERT INTO order_detail 
                (order_id, price, favorable_price, car_detail) 
                VALUES (?, ?, ?, ?)
            `;
          pools({sql, val:[
                  orderResult.result.insertId,
                  price || 0,
                  favorable_price || 0,
                  car_detail || ''
              ],run:true,res,req}).then(res => {
                  //减少对应车型的库存

                sql = `update vehicleinventory set stock_quantity = stock_quantity -1 where  model = ?`
              pools({sql,val:[vehicle_model],run:false,res,req})
          })

          res.json(utils.returnData(1, '添加成功'));
      })




    } catch (error) {
        console.error('添加订单失败:', error);
        res.json(utils.error('添加订单失败'));
    }
});

// 编辑订单
router.post('/edit', async (req, res) => {
    try {
        const {
            id,
            customer_name,
            vehicle_model,
            order_status,
            payment_status,
            // 订单详情数据
            price,
            favorable_price,
            car_detail
        } = req.body;

        // 参数验证
        if (!id || !customer_name || !vehicle_model) {
            return res.json(utils.error('订单ID、客户姓名和车型不能为空'));
        }


            // 1. 更新主订单表
            let sql = `
                UPDATE salesorder 
                SET customer_name = ?, 
                    vehicle_model = ?, 
                    order_status = ?, 
                    payment_status = ?
                WHERE id = ?
            `;
        pools({sql, val:[
                customer_name,
                vehicle_model,
                order_status,
                payment_status,
                id
            ],run:false,res,req});

            // 2. 更新订单详情表
        sql = `
                UPDATE order_detail 
                SET price = ?,
                    favorable_price = ?,
                    car_detail = ?
                WHERE order_id = ?
            `;
            console.log(sql)
        console.log(req.body)
            await pools({sql, val:[
                price || 0,
                favorable_price || 0,
                car_detail || '',
                id
            ],run:false,res,req});

            res.json(utils.returnData(1, '更新成功'));

    } catch (error) {
        console.error('编辑订单失败:', error);
        res.json(utils.error('编辑订单失败'));
    }
});

// 删除订单
router.post('/delete', async (req, res) => {
    try {
        const { id } = req.body;

        // 参数验证
        if (!id) {
            return res.json(utils.error('订单ID不能为空'));
        }

        // 1. 删除订单详情
        let sql  = 'DELETE FROM order_detail WHERE order_id = ?';
        await  pools({sql, val:[id],run:true,res,req}).then(result => {
            // 2. 删除主订单
            sql = 'DELETE FROM salesorder WHERE id = ?';
            pools({sql, val:[id],res,req});
        })

        res.json(utils.returnData(1, '删除成功'));

    } catch (error) {
        console.error('删除订单失败:', error);
        res.json(utils.error('删除订单失败'));
    }
});



module.exports = router;
